<?php

namespace App\Http\Controllers\forum;

use App\models\forum\Partition;
use App\models\forum\Topic;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;

class ForumController extends Controller
{
    public function index(){
        $partitions = Partition::getForumPartitions();
        return view('forum.index', compact('partitions'));
    }

    public function plate($id, Request $request){
        if (is_integer(intval($id)) <= 0){
            return view('errors.404');
        }
        $partition = Partition::find($id);
        if (empty($partition)){
            return view('errors.404');
        }
        if ($this->verifyPermissions($partition->flag) == false){
            return view('errors.norole');
        }
        $read_flag = 0;
        if (Auth::check() == true){
            $read_flag = Auth::user()->read_flag;
        }
        if ($request->has('categorie')){
            $categorie_id   = $request->get('categorie');
            $topics         = Topic::where('pid', $partition->id)
                ->where('read_flag', '<=', $read_flag)
                ->where('category_id', $categorie_id)
                ->where('is_delete', 0)
                ->orderBy('created_at', 'DESC')
                ->paginate(30);
        }else{
            $categorie_id   = 0;
            $topics         = Topic::where('pid', $partition->id)
                ->where('read_flag', '<=', $read_flag)
                ->where('is_delete', 0)
                ->orderBy('created_at', 'DESC')
                ->paginate(30);
        }
        $categorie      = $partition->partitionCategorie()->get();
        return view('forum.plate', compact('partition', 'topics', 'categorie', 'categorie_id'));
    }

    public function getMigration(Request $request){
        $v = Validator::make($request->all(),[
            'id'        => 'required|integer|exists:partitions,id'
        ]);

        if ($v->fails()){
            return ['code' => '-100000', 'msg' => '参数不合法'];
        }
        $partition = Partition::find($request->get('id'));

        return ['code' => '0', 'msg' => $partition->partitionCategorie()->first()->categorie()->get()];
    }

    protected function verifyPermissions($flag){
        if ($flag <= 0){
            return true;
        }
        $userRole = Auth::user()->userRole()->first();
        if (empty($userRole)){
            return false;
        }
        $role = $userRole->role()->first();
        if (empty($role)){
            return false;
        }

        if ($flag & $role->flag) {
            return true;
        }
        return false;
    }
}
